package com.example.lin.qq_home_project.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HttpUtils {

    private static ExecutorService pool;

    static {
        pool = Executors.newFixedThreadPool(100);
    }

    private static String TAG = "HttpUtils";

    public static void get(String address, Map<String, String> params, OnHttpCallback callback) {
        StringBuilder sb = new StringBuilder(address);
        if (!address.endsWith("?"))
            sb.append("?");
        String s = formatParams(params);
        sb.append(s);
        get(sb.toString(), callback);
    }


    public interface OnHttpCallback {
        void onSuccess(String response);

        void onFailure(String error);
    }




    public static void get(final String address, final OnHttpCallback callback) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection conn = null;
                BufferedReader br = null;
                try {
                    URL url = new URL(address);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");//POST
                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
//                        return sb.toString();
                        if (callback != null) {
                            callback.onSuccess(sb.toString());
                        }
                    } else {
                        if (callback != null) {
                            callback.onFailure("响应码为:" + responseCode);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onFailure(e.getMessage());
                    }
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
            }
        });
    }


    private static String formatParams(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String, String>> set = map.entrySet();
        for (Map.Entry<String, String> entry : set) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        sb.delete(sb.length() - 1, sb.length());
        return sb.toString();
    }

    public static void post(final String address, final Map<String, String> map, final OnHttpCallback callback) {

        pool.execute(new Runnable() {
            @Override
            public void run() {

                //需要写给服务器的内容
                String content = formatParams(map);

                BufferedReader br = null;
                HttpURLConnection conn = null;
                BufferedWriter bw = null;
                try {
                    URL url = new URL(address);
                    Log.e(TAG, "run: "+address );
                    conn = (HttpURLConnection) url.openConnection();

                    //请求方式为 POST
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);//链接超时  5000毫秒

                    //POST  HTTP 请求头
                    conn.setRequestProperty("accept", "*/*");
                    conn.setRequestProperty("connection", "Keep-Alive");
                    conn.setRequestProperty("Content-Length", content.length() + "");
//                    conn.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length));

                    //打开输出流
                    conn.setDoInput(true);
                    conn.setDoOutput(true);

                    //传递数据给服务器
                    bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
                    bw.write(content);
                    Log.e(TAG, "run: "+content);
                    bw.flush();

                    int responseCode = conn.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        StringBuilder sb = new StringBuilder();
                        String line;
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                        if (callback != null) {
                            callback.onSuccess(sb.toString());
                        }
                    } else {
                        if (callback != null) {
                            callback.onFailure("响应码为:" + responseCode);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    if (callback != null) {
                        callback.onFailure(e.getMessage());
                    }
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (bw != null) {
                        try {
                            bw.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (conn != null) {
                        conn.disconnect();
                    }
                }
//                return null;
            }
        });
    }

}
